const axios = require('axios');

const NODES = [
    'http://localhost:3000',
    'http://localhost:3001',
    'http://localhost:3002'
];

async function clusterDemo() {
    console.log('=== 集群演示 ===\n');

    try {
        // 1. 检查所有节点健康状态
        console.log('1. 检查节点健康状态...');
        for (const node of NODES) {
            try {
                const response = await axios.get(`${node}/health`);
                console.log(`✅ ${node}: ${response.data.status}`);
            } catch (error) {
                console.log(`❌ ${node}: 无法连接`);
            }
        }
        console.log();

        // 2. 在节点1写入数据
        console.log('2. 在节点1写入数据...');
        await axios.post(`${NODES[0]}/cache`, {
            key: 'cluster:test',
            value: { message: '这是集群测试数据', timestamp: Date.now() },
            ttl: 300000 // 5分钟
        });
        console.log('✅ 数据已写入节点1\n');

        // 3. 等待同步
        console.log('3. 等待数据同步...');
        await new Promise(resolve => setTimeout(resolve, 2000));

        // 4. 从所有节点读取数据
        console.log('4. 从所有节点读取数据...');
        for (let i = 0; i < NODES.length; i++) {
            try {
                const response = await axios.get(`${NODES[i]}/cache/cluster:test`);
                console.log(`✅ 节点${i+1} (${NODES[i]}):`, response.data.value);
            } catch (error) {
                if (error.response && error.response.status === 404) {
                    console.log(`⚠️  节点${i+1} (${NODES[i]}): 数据未找到`);
                } else {
                    console.log(`❌ 节点${i+1} (${NODES[i]}): 读取失败`);
                }
            }
        }
        console.log();

        // 5. 查看各节点的集群视图
        console.log('5. 查看集群状态...');
        for (let i = 0; i < NODES.length; i++) {
            try {
                const response = await axios.get(`${NODES[i]}/nodes`);
                console.log(`✅ 节点${i+1} 集群状态:`, {
                    currentNode: response.data.currentNode.id.substring(0, 8) + '...',
                    nodesCount: response.data.nodes.length
                });
            } catch (error) {
                console.log(`❌ 节点${i+1}: 无法获取集群状态`);
            }
        }

    } catch (error) {
        console.error('❌ 演示失败:', error.response?.data || error.message);
    }
}

// 运行演示
if (require.main === module) {
    clusterDemo();
}

module.exports = clusterDemo;
